import random
import string
randrange = random.randrange

WHITESPACE = ' \t\r\n'

rec = 11 

def spaces(count=3):
	return ' ' * count

def whitespace(count=3):
    return ''.join([random.choice(WHITESPACE) for i in range(count)])
    
def randname():
   	return ''.join(random.choice(string.ascii_lowercase) for i in range(10))

def randop():
    a = randrange(3)
    if (a == 0):
        return '+'
    if (a == 1):
	    return '-'
    return '*'
    
def gen_expr_with_spaces(depth=3, maxnum=5, length=8, space_count=2):
    def gen_aux(depth):
        if depth == 0:
            return str(randrange(maxnum))
        else:
            cur = length-1
            s = gen_aux(depth-1)
            for i in range(cur):
                s += whitespace(space_count) + randop() + whitespace(space_count) + gen_aux(depth-1)
            return '(' + whitespace(space_count) + s + whitespace(space_count) + ')'
    global rec
    if (rec == 0):
        depth = 1
    return gen_aux(depth)
    
def gen_expr(depth=3, maxnum=5, length=5):
    def gen_aux(depth):
        if depth == 0:
            return str(randrange(maxnum))
        else:
            cur = length-1
            s = gen_aux(depth-1)
            for i in range(cur):
                s += randop() + gen_aux(depth-1)
            return '(' + s + ')'
    global rec
    if (rec == 0):
        depth = 1;
    return gen_aux(depth)

def gen_if():
    def aux(t):
        if t == 0:
            return '<'
        else:
            return '>' 
    return 'IF ' + '[' + gen_expr_with_spaces() + aux(randrange(2)) + gen_expr_with_spaces() + ']' + gen_block() + spaces(2) + gen_block();
    
def gen_block(st=4):
    global rec
    rec -= 1
    if (rec == 0):
        rec += 1
        return empty_block()
    a = '{';
    for i in range(st-1):
        a += gen_statement() + ' ;\n '
    a += gen_statement() + ' } '
    rec += 1
    return a
    
def empty_block():
    return '{ PASS }'
    
def gen_statement():
    global rec
    a = randrange(5)
    if (rec == 0):
        a = 4
    if (a == 0):
        return gen_block(3)
    if (a == 1):
        return gen_if()
    if (a == 2):
        return 'aflkjef    =     ' + gen_expr_with_spaces()
    if (a == 3):
        return ' RET ' + gen_expr_with_spaces()
    if (a == 4):
        return ' PASS '
    

def gen_args(num):
    a = ''
    for i in range(num-1):
        a += randname() + ' , '
    if num > 0:
        a += randname()
    return a
        
def gen_func():
    return 'DEF ' + whitespace() + randname() + ' ( ' + whitespace() + gen_args(10) + whitespace() + ' ) ' + gen_block(2) + '   \n'
    
def gen_prog(func=10):
    a = 'test ;\n'
    for i in range(func):
        a += gen_func()
    return a
        
def main():
    num = 2  
    p = gen_prog()
    with open('prog5.txt', 'w') as f:
        f.write(p)

if __name__ == '__main__':
    main()
